package com.huaboot.generator.controller;

import cn.hutool.core.io.IoUtil;
import com.huaboot.commont.core.BaseResponse;
import com.huaboot.commont.core.ResultUtils;
import com.huaboot.commont.exception.BusinessException;
import com.huaboot.commont.exception.ErrorCode;
import com.huaboot.commont.page.PageResult;
import com.huaboot.generator.entity.TableEntity;
import com.huaboot.generator.entity.TableFieldEntity;
import com.huaboot.generator.mapper.TableMapper;
import com.huaboot.generator.query.GeneratorQuery;
import com.huaboot.generator.service.GeneratorService;
import com.huaboot.generator.service.TableFieldService;
import com.huaboot.generator.utils.GenUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipOutputStream;

/**
 * description: 数据源+表+表字段管理管理
 * date: 2023/8/12 15:03
 * author: ff
 */

@Slf4j
@RestController
@Tag(name = "代码生成")
@RequestMapping("generator")
public class GeneratorController {

    @Autowired
    private GeneratorService generatorService;

    @Autowired
    private TableFieldService tableFieldService;

    @Autowired
    private TableMapper tableMapper;


    /**
     * 获取全部数据表分页
     */
    @GetMapping("/table/page")
    @Operation(summary = "获取全部数据表分页")
    public BaseResponse<PageResult<TableEntity>> getAllTables(GeneratorQuery generatorQuery){
        return ResultUtils.success(generatorService.getAllTableList(generatorQuery));
    }

    /**
     * 获取所有数据表数据
     */
    @GetMapping("/table/list")
    public BaseResponse<List<TableEntity>> tableList() {
        try {
            // 根据数据源，获取全部数据表
            List<TableEntity> tableList = generatorService.getTableList();
            return ResultUtils.success(tableList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("获取数据库所有表错误！");
        }
    }

    /**
     * 获取表信息
     */
    @GetMapping("/table/info/{id}")
    @Operation(summary = "获取表信息")
    public BaseResponse<TableEntity> getTableInfoById(@PathVariable("id") Long id){
        TableEntity table = tableMapper.selectById(id);
        // 获取表的字段
        List<TableFieldEntity> fieldList = tableFieldService.getTableFieldListByTableId(table.getId());
        table.setFieldList(fieldList);
        return ResultUtils.success(table);
    }

    /**
     * 表同步
     * 1。查询当前表的字段信息
     * 2。比对之前入库的表信息，多的增加入库  少了就删除库中的数据
     */
    @Operation(summary = "表同步")
    @GetMapping("table/sync/{id}")
     public  BaseResponse<?> syncTable(@PathVariable("id") Long id) {
         generatorService.syncTable(id);
         return ResultUtils.success("同步成功");
     }


    /**
     * 导入
     * 1。查询出当前数据库中的所有表
     * 2。可以多选表，导入准备生成
     * 3。表不存在就入库，存在拦截给提示
     * 4。入库时，做校验字段格式匹配
     */
    @PostMapping("/table/import")
    @Operation(summary = "表导入")
    public  BaseResponse<?> tableImport(@RequestBody List<String> tableNameList) {
        generatorService.tableImport(tableNameList);
        return ResultUtils.success("导入成功");
    }

    @GetMapping("/code/download")
    @Operation(summary = "代码下载")
    public  void codeDownload(String tableIdList, HttpServletResponse response)  {
        byte[] data = generatorService.codeDownload(tableIdList);
        try {
            genCode(response, data);
        }catch (Exception e){
            log.error("下载异常：",e);
            throw new BusinessException(ErrorCode.GENERATOR_ERROR,"下载失败");
        }
    }

    /**
     * 修改表字段数据
     *
     * @param tableId        表ID
     * @param tableFieldList 字段列表
     */
    @PutMapping("field/{tableId}")
    @Operation(summary = "修改表字段数据")
    public BaseResponse<?> updateTableField(@PathVariable("tableId") Long tableId, @RequestBody List<TableFieldEntity> tableFieldList) {
        tableFieldService.updateTableField(tableId, tableFieldList);
        return ResultUtils.success();
    }

    /**
     * 修改
     *
     * @param table 表信息
     */
    @PostMapping("tableInfo/update")
    public BaseResponse<?> update(@RequestBody TableEntity table) {
        tableMapper.updateById(table);
        return ResultUtils.success();
    }


    /**
     * 删除
     *
     * @param ids 表id数组
     */
    @DeleteMapping("tableInfo/delete")
    public BaseResponse<?> delete(@RequestBody Long[] ids) {
        tableMapper.deleteBatchIds(Arrays.asList(ids));
        return ResultUtils.success();
    }

    /**
     * 数据库字段映射列表
     * @return
     */
    @GetMapping("fieldtype/list")
    public BaseResponse<Set<String>> list() {
        Set<String> set = tableFieldService.getList();

        return ResultUtils.success(set);
    }
    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException
    {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"huaBoot.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}
